﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Volo.Abp.Application.Dtos;
using Volo.Abp.Application.Services;
using Dapper;
using Volo.Abp.Dapper;
using System.Data;
using Microsoft.Data.SqlClient;
using Logistics.Model;
using Volo.Abp.Domain.Repositories;
using System.Configuration;
using MySqlConnector;

namespace Logistics.Track
{
    public class CarryTrackAppService : ApplicationService, ICarryTrackAppService
    {
        private readonly IRepository<Carriercontracttracking, int> _carryRepository;
        private readonly ICarryTrackRepository _carrytrack;
        public CarryTrackAppService(IRepository<Carriercontracttracking, int> carryRepository, ICarryTrackRepository carrytrack)
        {
            _carryRepository = carryRepository;
            _carrytrack = carrytrack;
        }
        public async Task<PagedResultDto<CarryTrackDto>> GetDapperCarryTracks(CarryTrackSearchDto csd)
        {
            string sql = "select a.*,b.NumberId,b.ContractTitle,b.OutsourcingUnit,b.OutsourcingLeader,b.Line,b.Freightrate,b.CharterConditions,b.CharterAmount,b.SigningDate,b.`Handler`,b.CreationTime,c.`Name` Fname,d.`Name` Oname,e.`Name` Lname from Carriercontracttracking a join Carry b on a.ContractId=b.Id join field c on b.OutsourcingUnit=c.Id join `owner` d on b.OutsourcingLeader=d.Id join line e on b.Line=e.Id where 1=1 ";
            string sql1 = sql+ " order by b.Id limit " + csd.MaxResultCount + ","+csd.SkipCount;
            using(IDbConnection conn = new MySqlConnection("Server=10.31.64.9;Port=3306;Database=Logistics;Uid=si;Pwd=111111;"))
            {
                conn.Open();
                var count=(List<CarryTrackDto>)await conn.QueryAsync<CarryTrackDto>(sql1);
                int totalCount=count.Count();
                var list= (List<CarryTrackDto>)await conn.QueryAsync<CarryTrackDto>(sql);
                return new PagedResultDto<CarryTrackDto>(
                  totalCount,
                  list.ToList()
                );
            }
        }

        public async Task<int> UpdateCarryTrack(int Id, string Condition)
        {
            var carrytract = _carrytrack.GetCarryTrackById(Id).Result;
            carrytract.Condition = Condition;
            int result = await _carrytrack.Update(carrytract);
            return result;
        }
        public async Task<Line> GetLineById(int Id)
        {
            var list= _carrytrack.GetLineById(Id).Result;
            return list;
        }
    }
}
